package com.kb.erp.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.dynamic.datasource.annotation.DS;

import com.kb.erp.entity.pcbout.*;
import com.kb.erp.mapper.sqlServer.K3Mapper;
import com.kb.erp.mapper.sqlServer.PCBOutMapper;
import com.kb.erp.service.PCBOutService;

import com.kb.erp.util.HttpUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@DS("slave-1")
public class PCBOutServiceImpl implements PCBOutService {

    @Resource
    private PCBOutMapper pcbOutMapper;

    @Resource
    private K3Mapper k3Mapper;



    @Override
    public List<K3WorkShop> getWorkShop(){
        return pcbOutMapper.getWorkShops();
    }



    private double parseToTwoSignificantDigits(String value) {
        if (value == null || value.isEmpty()) {
            return 0.0;
        }

        double number = Double.parseDouble(value);
        BigDecimal bd = new BigDecimal(number);
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }


    public static String processString(String input) {
        // 统计短横线的数量
        int dashCount = input.length() - input.replace("-", "").length();

        // 如果短横线超过2个，则截取到第二个短横线
        if (dashCount > 2) {
            int secondDashIndex = input.indexOf("-", input.indexOf("-") + 1); // 找到第二个短横线
            int thirdDashIndex = input.indexOf("-", secondDashIndex + 1); // 找到第三个短横线

            // 如果有第三个短横线，截取到第二个短横线位置
            if (thirdDashIndex != -1) {
                return input.substring(0, thirdDashIndex);
            }
        }

        // 如果短横线不超过2个，直接返回原字符串
        return input;
    }

    @Override
    public List<QueryVO> query(QueryTO to) {


        if(StringUtils.isNotBlank(to.getWorkOrderNumber())){


            to.setWorkOrderNumber(processString(to.getWorkOrderNumber()));

        }



        List<QueryVO> queryVOS = pcbOutMapper.selectWorkOrders(to);

        return queryVOS.stream()
                .filter(vo -> {
                    // Filter out the items where plateThickness is "0" or "0.0"
                    String plateThickness = vo.getPlateThickness();
                    return StringUtils.isNotBlank(plateThickness)&&(!(plateThickness.equals("0") || plateThickness.equals("0.0"))) ;
                })
                .map(vo -> {
                    // 将 length 和 width 转为 Double，保留两位有效数字
                    double length = parseToTwoSignificantDigits(vo.getLength());
                    double width = parseToTwoSignificantDigits(vo.getWidth());

                    // 计算面积
                    double area = length * width;

                    // 保留两位有效小数
                    area = new BigDecimal(area).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                    if(vo.getBomQuan()!=null&&StringUtils.isNotBlank(vo.getCopperThickness())){


                        vo.setTotal((int) (vo.getBomQuan()*vo.getPnlCutQuan()));


                    }else{
                        vo.setTotal(0);
                    }

                    vo.setLength(String.valueOf((int) length));
                    vo.setWidth(String.valueOf((int) width));

                    // 设置面积
                    vo.setArea(area);
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<Material> queryBomList(String plate, String type) {

        return  pcbOutMapper.queryBomList(plate,type);

    }


    @Override
    public Material queryBomByNo(String no) {

        return  pcbOutMapper.queryBomByNo(no);

    }

    @Override
    public void mounthusecal() {


        pcbOutMapper.clearMonthUseTable();

        List<MonthUse> monthUses = k3Mapper.selectMonthUseData();

        monthUses = monthUses.stream()
                .map(monthUse -> {
                    // 获取 qty 字段并转换为 BigDecimal
                    String qty = monthUse.getQty();
                    if (qty != null && !qty.isEmpty()) {
                        // 处理科学计数法格式
                        BigDecimal qtyDecimal = new BigDecimal(qty);
                        // 保留两位小数
                        qtyDecimal = qtyDecimal.setScale(2, RoundingMode.HALF_UP);
                        // 如果小于 0，则设置为 0
                        if (qtyDecimal.compareTo(BigDecimal.ZERO) < 0) {
                            qtyDecimal = BigDecimal.ZERO;
                        }
                        // 设置回 MonthUse 对象
                        monthUse.setQty(qtyDecimal.toString());
                    }
                    return monthUse;
                })
                .collect(Collectors.toList());


        List<List<MonthUse>> batches = splitIntoBatches(monthUses, 500);
        for (List<MonthUse> batch : batches) {
            pcbOutMapper.insertList(batch);
        }


    }


    private <T> List<List<T>> splitIntoBatches(List<T> list, int batchSize) {
        List<List<T>> batches = new ArrayList<>();
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            batches.add(list.subList(i, end));
        }
        return batches;
    }


}
